package redis.inaction.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import redis.inaction.spring.ops.RedisRepositoryOps;
import redis.inaction.spring.ops.RedisTemplateOps;
import redis.inaction.spring.ops.SpringCacheOps;

import java.util.concurrent.TimeUnit;

@Slf4j
@SpringBootApplication
@EnableRedisRepositories
@EnableCaching(proxyTargetClass = true)
public class DemoApplication implements ApplicationRunner {

	@Autowired
	private RedisTemplateOps redisTemplateOps;

	@Autowired
	private RedisRepositoryOps redisRepositoryOps;

	@Autowired
	private SpringCacheOps springCacheOps;

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
//		redisTemplateOps();
//		redisRepositoryOps();
		springCacheOps();
	}

	private void redisTemplateOps(){
		log.info("get city: {}",redisTemplateOps.getCity("110100000000"));
		log.info("get city: {}",redisTemplateOps.getCity("110100000000"));
		log.info("get city: {}",redisTemplateOps.getCity("110100000000"));
	}

	private void redisRepositoryOps(){
		log.info("RedisRepository ops..");
		log.info("get city: {}",redisRepositoryOps.getCity("310100000000"));
		log.info("get city: {}",redisRepositoryOps.getCity("310100000000"));
		log.info("get city: {}",redisRepositoryOps.getCity("310100000000"));
	}

	private void springCacheOps() throws Exception{
		log.info("CpringCacheOps ops..");
		log.info("get city: {}",springCacheOps.getCity("440300000000"));
		log.info("get city: {}",springCacheOps.getCity("440300000000"));
		log.info("get city: {}",springCacheOps.getCity("440300000000"));

		log.info("wait for cache invalid...");
		TimeUnit.SECONDS.sleep(10);
		log.info("get city: {}",springCacheOps.getCity("440300000000"));

	}
}

